import com.alibaba.fastjson2.JSONObject;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletableFuture;
import java.util.zip.GZIPInputStream;

/**
 * 火币WebSocket诊断程序
 * 用于测试火币WebSocket连接和数据接收
 */
public class HuobiWebSocketDiagnosis {
    
    public static void main(String[] args) {
        try {
            System.out.println("开始火币WebSocket诊断测试...");
            
            // 火币WebSocket地址
            String websocketUrl = "wss://api.huobi.pro/ws";
            URI websocketUri = URI.create(websocketUrl);
            
            System.out.println("连接地址: " + websocketUrl);
            
            // 创建WebSocket客户端
            WebSocketClient client = new WebSocketClient(websocketUri, new Draft_6455()) {
                @Override
                public void onOpen(ServerHandshake handshake) {
                    System.out.println("✅ 火币WebSocket连接已打开");
                    System.out.println("状态码: " + handshake.getHttpStatus());
                    System.out.println("状态信息: " + handshake.getHttpStatusMessage());
                    
                    // 等待2秒后开始订阅
                    CompletableFuture.runAsync(() -> {
                        try {
                            Thread.sleep(2000);
                            
                            // 订阅BTC的24小时行情数据
                            JSONObject subMsg = new JSONObject();
                            subMsg.put("sub", "market.btcusdt.detail");
                            subMsg.put("id", "btc_detail_" + System.currentTimeMillis());
                            
                            String subscriptionMessage = subMsg.toString();
                            System.out.println("📤 发送订阅消息: " + subscriptionMessage);
                            
                            send(subscriptionMessage);
                            
                            // 再订阅ETH的K线数据
                            Thread.sleep(1000);
                            JSONObject subMsg2 = new JSONObject();
                            subMsg2.put("sub", "market.ethusdt.kline.1min");
                            subMsg2.put("id", "eth_kline_" + System.currentTimeMillis());
                            
                            String subscriptionMessage2 = subMsg2.toString();
                            System.out.println("📤 发送订阅消息: " + subscriptionMessage2);
                            
                            send(subscriptionMessage2);
                            
                        } catch (Exception e) {
                            System.err.println("❌ 订阅失败: " + e.getMessage());
                            e.printStackTrace();
                        }
                    });
                }
                
                @Override
                public void onMessage(String message) {
                    System.out.println("📨 收到文本消息: " + message);
                    
                    try {
                        JSONObject jsonObject = JSONObject.parseObject(message);
                        
                        // 处理ping消息
                        if (jsonObject.containsKey("ping")) {
                            long pingTime = jsonObject.getLong("ping");
                            JSONObject pong = new JSONObject();
                            pong.put("pong", pingTime);
                            send(pong.toString());
                            System.out.println("💓 收到ping，发送pong: " + pingTime);
                            return;
                        }
                        
                        // 处理订阅确认
                        if (jsonObject.containsKey("subbed")) {
                            System.out.println("✅ 订阅成功: " + jsonObject.getString("subbed"));
                            return;
                        }
                        
                        // 处理订阅错误
                        if (jsonObject.containsKey("status") && "error".equals(jsonObject.getString("status"))) {
                            System.err.println("❌ 订阅失败: " + message);
                            return;
                        }
                        
                        // 处理数据推送
                        if (jsonObject.containsKey("ch")) {
                            String channel = jsonObject.getString("ch");
                            System.out.println("📊 收到数据推送: " + channel);
                            
                            if (channel.contains("detail")) {
                                System.out.println("📈 24小时行情数据: " + message);
                            } else if (channel.contains("kline")) {
                                System.out.println("📊 K线数据: " + message);
                            }
                        }
                        
                    } catch (Exception e) {
                        System.err.println("❌ 处理消息失败: " + e.getMessage());
                        e.printStackTrace();
                    }
                }
                
                @Override
                public void onMessage(ByteBuffer bytes) {
                    System.out.println("📨 收到二进制消息，大小: " + bytes.remaining() + " 字节");
                    
                    try {
                        // 解压GZIP数据
                        String decompressed = decompress(bytes.array());
                        System.out.println("📤 解压后的消息: " + decompressed);
                        
                        // 处理解压后的消息
                        onMessage(decompressed);
                        
                    } catch (Exception e) {
                        System.err.println("❌ 解压消息失败: " + e.getMessage());
                        e.printStackTrace();
                    }
                }
                
                @Override
                public void onClose(int code, String reason, boolean remote) {
                    System.out.println("❌ 连接关闭");
                    System.out.println("关闭码: " + code);
                    System.out.println("关闭原因: " + reason);
                    System.out.println("远程关闭: " + remote);
                }
                
                @Override
                public void onError(Exception ex) {
                    System.err.println("❌ 连接错误: " + ex.getMessage());
                    ex.printStackTrace();
                }
            };
            
            // 连接到WebSocket
            System.out.println("🔗 尝试连接到火币WebSocket...");
            boolean connected = client.connectBlocking();
            
            if (connected) {
                System.out.println("✅ 连接成功，等待数据...");
                
                // 保持连接60秒
                Thread.sleep(60000);
                
                client.close();
                System.out.println("🔚 测试完成");
            } else {
                System.err.println("❌ 连接失败");
            }
            
        } catch (Exception e) {
            System.err.println("❌ 诊断程序异常: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 解压GZIP数据
     */
    private static String decompress(byte[] data) throws Exception {
        try (ByteArrayInputStream bis = new ByteArrayInputStream(data);
             GZIPInputStream gzis = new GZIPInputStream(bis);
             ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            
            byte[] buffer = new byte[1024];
            int len;
            while ((len = gzis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            
            return bos.toString("UTF-8");
        }
    }
} 